package com.company.ems.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            // 初始化失败时抛出运行时异常，避免后续使用null的sqlSessionFactory
            throw new RuntimeException("初始化MyBatis失败", e);
        }
    }

    public static SqlSession getSqlSession() {
        // 添加空指针检查
        if (sqlSessionFactory == null) {
            throw new RuntimeException("SqlSessionFactory尚未初始化");
        }
        return sqlSessionFactory.openSession();
    }
}